/**
 * @Title: index.js
 * @Description: index
 * @author: Fanchao
 * @date: 2020/12/14 9:18 上午
 * @version V1.0
 */
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Button, DatePicker, Form, message, Modal, Popconfirm, Select, Table } from 'antd';
import {
    deleteTrainingType,
    getCourseList,
    getTeacherUserModelList,
    getTeachClassList,
    getSchoolYearList,
    getRunCourseList,
    createRunCourse,
    getRunTrainTaskInfoList,
    getTrainingTypeList
} from 'api/index';
import SectionTitle from 'components/SectionTitle';
import AddSomeButton from 'components/AddSomeButton';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
};
const Running = () => {
    const [trainingTypeList, setTrainingTypeList] = useState([]);
    const [runTrainTaskInfoList, setRunTrainTaskInfoList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [visible, setVisible] = useState(false);
    const [courseList, setSourseList] = useState([]);
    const [teacherOptions, setTeacherOptions] = useState([]);
    const [teachClassList, setTeachClassList] = useState([]);
    const [schoolYearListOption, setSchoolYearListOption] = useState([]);
    const [form] = Form.useForm();

    const fetchRunTrainTaskInfoList = async (filter) => {
        const result = await getRunTrainTaskInfoList({ trainingTypeId: filter });
        if (result.status === "success") {
            const runTrainTaskInfoList = result.result;
            setRunTrainTaskInfoList(runTrainTaskInfoList);
        } else {
            message.error(result.message);
        }
    };
    const fetchCourseList = async (filter) => {
        const result = await getCourseList({majorId:filter});
        if (result.status === 'success') {
            const courseList = result.result;
            setSourseList(courseList);
        } else {
            message.error(result.message);
        }
    };
    const fetchTrainingTypeList = async () => {
        const result = await getTrainingTypeList();
        if (result.status === "success") {
            const trainingTypeList = result.result;
            setTrainingTypeList(trainingTypeList);
        } else {
            message.error(result.message);
        }
    };

    const fetchTeachClassList = async () => {
        const result = await getTeachClassList();
        if (result.status === 'success') {
            const teachClassList = result.result;
            setTeachClassList(teachClassList);
        } else {
            message.error(result.message);
        }
    };
    const fetchSchoolYearListOption = async () => {
        const result = await getSchoolYearList();
        if (result.status === 'success') {
            const schoolYearListOption = result.result;
            setSchoolYearListOption(schoolYearListOption);
        } else {
            message.error(result.message);
        }
    };
    const fetch = async () => {
        setLoading(true);
        const result = await getRunCourseList();
        if (result.status === 'success') {
            const dataSource = result.result;
            setDataSource(dataSource);
        } else {
            message.error(result.message);
        }
        setLoading(false);
    };
    const fetchTeacher = async () => {
        const result = await getTeacherUserModelList();
        if (result.status === 'success') {
            const teacherOptions = result.result;
            setTeacherOptions(teacherOptions);
        } else {
            message.error(result.message);
        }
    };

    useEffect(() => {
        fetch();
    }, []);
    const addItem = () => {
        setVisible(true);
        fetchTrainingTypeList();
        fetchTeachClassList();
        fetchSchoolYearListOption();
        fetchTeacher();
    };
    const handleDelete = async ({ trainTypeId }) => {
        const result = await deleteTrainingType({ trainingTypeId: trainTypeId });
        if (result.status === 'success') {
            message.success('删除成功');
            fetch();
        } else {
            message.error(result.message);
        }
    };
    const title = '新增课程运行信息';
    const columns = [
        {
            title: '课程运行名称',
            dataIndex: 'courseName',
            align: 'left',
        },
        {
            title: '学年',
            dataIndex: 'schoolYear',
            align: 'left',
        },
        {
            title: '学期',
            dataIndex: 'semester',
            align: 'left',
        },

        {
            title: '课程开始时间',
            dataIndex: 'startDate',
            align: 'left',
        },
        {
            title: '课程结束时间',
            dataIndex: 'endDate',
            align: 'left',
        },
        // {
        //     title: '操作',
        //     align: 'left',
        //     render: (item) => {
        //         return (
        //             <div>
        //                 <Popconfirm title="是否要删除？" onConfirm={() => handleDelete(item)}>
        //                     <Button style={{ padding: 2, color: '#C21217', fontWeight: 'bold' }} type="link">删除</Button>
        //                 </Popconfirm>
        //
        //             </div>
        //         );
        //     },
        // },
    ];
    return (
        <div className={styles.pageContainer}>
            <div className={styles.pageContainerHeader}>
                <SectionTitle title={title}/>
                <div style={{ width: '220px' }} onClick={() => addItem({})}>
                    <AddSomeButton title={title}/>
                </div>
            </div>
            <div className={styles.pageContainerTable}>
                <SectionTitle title={'已有课程运行信息'}/>
                <div className={styles.tableContainer}>
                    <Table
                        bordered={false} // 是否有边框
                        rowKey='courseId' // 唯一key值
                        loading={loading} // 加载动画
                        columns={columns} // 表头
                        dataSource={dataSource}
                        pagination={false}
                    />
                </div>
            </div>
            <Modal
                title={title}
                visible={visible}
                width="860px"
                onOk={() => {
                    form.validateFields().then(async values => {
                        // values.startDate = moment(values.time[0]).valueOf();
                        values.startDate = moment(values.time[0]).format('YYYY-MM-DD');
                        // values.endDate = moment(values.time[1]).valueOf();
                        values.endDate = moment(values.time[1]).format('YYYY-MM-DD');
                        delete values.time;
                        const result = await createRunCourse(values);
                        if (result.status === 'success') {
                            setVisible(false);
                            fetch();
                        } else {
                            message.error(result.message);
                        }
                    }).catch(info => {
                        // console.log(info);
                    });
                }}
                onCancel={() => {
                    form.resetFields();
                    setVisible(false);
                }}
            >
                <Form
                    {...layout}
                    layout="horizontal"
                    form={form}
                    name="basic"
                    // 表单默认值，只有初始化以及重置时生效 莫用
                    initialValues={{
                        // name: itemData.name
                    }}
                >
                    <Form.Item
                        label="培训类型"
                        name="trainingTypeId"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Select
                            placeholder="培训类型"
                            onChange={(e) => {
                                fetchRunTrainTaskInfoList(e);
                            }}
                        >
                            {
                                trainingTypeList.map(item => {
                                    return <Option key={item.trainTypeId}
                                                   value={item.trainTypeId}>{item.trainingTypeName}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="任务运行"
                        name="runTrainTaskId"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Select
                            placeholder="任务运行信息"
                            onChange={(e) => {
                                fetchCourseList(e);
                            }}
                        >
                            {
                                runTrainTaskInfoList.map(item => {
                                    return <Option key={item.runTrainTaskId}
                                                   value={item.runTrainTaskId}>{item.majorSysCode} {item.majorName} {item.startDate}至{item.endDate}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="课程名称"
                        name="courseId"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="课程名称"
                        >
                            {
                                courseList.map(item => {
                                    return <Option key={item.courseId}
                                                   value={item.courseId}>{item.courseName}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="教员"
                        name="teacherUserIdList"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="教员"
                            mode="multiple"
                        >
                            {
                                teacherOptions.map(item => {
                                    return <Option key={item.teacherUserId}
                                                   value={item.teacherUserId}>{item.teacherRealName}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="schoolYear"
                        label="学年"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="请选择学年"
                        >
                            {
                                schoolYearListOption.map(item => {
                                    return <Option key={item.id} value={item.schoolYear}>{item.schoolYear}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="学期"
                        name="semester"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="请选择学期"
                        >
                            <Option value="第一学期">第一学期</Option>
                            <Option value="第二学期">第二学期</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="教学班"
                        name="teachClassIdList"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="教学班"
                            mode="multiple"
                        >
                            {
                                teachClassList.map(item => {
                                    return <Option key={item.teachClassId}
                                                   value={item.teachClassId}>{item.classNo}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="time"
                        label="课程开始结束时间"
                        rules={[{ type: 'array', required: true, message: '必填' }]}
                    >
                        <RangePicker
                            style={{ width: '100%' }}
                            showTime
                            format="YYYY-MM-DD"
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Running;
